package com.simplehc7878.warning.common;

import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result<?> handleServiceException(ServiceException e) {
        return Result.error(HttpStatus.UNPROCESSABLE_ENTITY.value(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError firstFieldError = e.getBindingResult().getFieldErrors().stream().findFirst().orElse(null);
        if (firstFieldError != null) {
            return Result.error(HttpStatus.BAD_REQUEST.value(), firstFieldError.getDefaultMessage());
        }
        return Result.error(HttpStatus.BAD_REQUEST.value(), "请求参数验证失败");
    }

    /*@ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        return Result.error(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "服务器内部错误: " + e.getMessage()
        );
    }*/
}
